#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "misc.h"
#include <time.h>

int main(int argc, char **argv){
	char buffer[80]= {0}, hexBuffer[80] = {0}, toHash[120] = {0};
	char  salt[7] = {0};
	char *toker = NULL, *cryptPswd = NULL;
	FILE *file = NULL;
	BasicHashFunctionPtr h = NULL;
	int hsize = 0;

	/*init. srand*/
	srand((unsigned int) time(0));
	/*check the no. of param. the user entered*/
	if (argc != 3) {
		fprintf(stderr, "Error: Usage create_salty_authentication <hash function name> <filename to create>\n");
		return 0;
	}

	/*parse the hash function name and assign h appropriately*/
	parseHashFunction(argv[1], &h, &hsize);
	if (h == NULL){
		fprintf(stderr, "Error: Hash %s is not supported\n", argv[1]);
		return 0;
	}

	if ((file = fopen(argv[2], "r")) != NULL){
		fclose(file);
		fprintf(stderr, "Error: File %s already exist\n", argv[2]);
		return 0;
	}

	/*check if something is wrong with the file*/
	if (!(file = fopen(argv[2], "w"))){
		perror(argv[2]);
		return 0;
	}

	fprintf(file, "%s\n", argv[1]);
	cryptPswd = (char *)calloc(hsize  +1,sizeof(char));
	if (cryptHash == NULL){
		fprintf(stderr, "error allocating mem. for the prog.\n");
		fclose(file);
		return 0;
	}

	while (1){
		printf(">>");
		readBuffer(buffer);
		if (strcmp(buffer,"quit") == 0) break;
		else if(*buffer == '\n') continue;
		else if (checkBuffer(buffer) == 0) {
			fprintf(stderr, "Error: Commands are either quit or <user name>tab<password>.\n");
			continue;
		}

		toker = strtok(buffer, "\t");
		fprintf(file, "%s\t", toker);
		toker = strtok(NULL, "\t");
		createSalt(salt);
		strcpy(toHash,toker);
		strcat(toHash,salt);
		cryptHash(*h, toHash, (unsigned char *)cryptPswd);
		binary2hexa((unsigned char *)cryptPswd, hsize, hexBuffer, 160);
		fprintf(file, "%s%s\n", hexBuffer, salt);
	}

	if (cryptPswd != NULL)
		free(cryptPswd);
	fclose(file);
	return 0;
}
